<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017-10-19
 * Time: 15:00
 */
namespace App\Http\Biz;
use App\Http\Model\ConsoleAccount;
use App\Http\Model\ConsoleAccountRole;
use App\Http\Model\PtGoods;
use App\Http\Model\PtGoodsSpec;
use App\Http\Model\PtPreSale;
use App\Http\Model\PtProv\PtProv;
use App\Http\Model\ShopAccount;
use App\Http\Model\ShopVcode;
use App\Http\Model\Supp;
use App\Http\Model\SuppAccountRoleMid;
use App\Http\Model\SuppDayStat;
use App\Http\Model\SuppPurchase;
use App\Http\Utils\Common\Consts;
use App\Http\Utils\Common\RoleUtils;
use App\Http\Utils\Common\SmsUtils;
use App\Http\Utils\Common\StringUtils;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Log;

class SuppBiz{

    //验证手机号是否已经存在
    public function validPhoneIsExist($phone){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');

            $count=ConsoleAccount::where('account',$phone)->count();

            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return $count;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }



    //注册
    public function register($params){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');

            if(!array_key_exists('psw',$params)||!array_key_exists('phone',$params)||
                !array_key_exists('contact',$params)||!array_key_exists('name',$params)||
                !array_key_exists('openid',$params)){

                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-1];//缺少参数
            }

            $psw=$params['psw'];
            $phone=$params['phone'];
            $contact=$params['contact'];
            $openid=$params['openid'];

            //2.判断用户手机号是否已经注册
            $phone_count=Supp::where('phone',$phone)->count();
            if($phone_count!=0){
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-3];
            }

            //插入数据
            $result=Supp::create(['phone' => $phone,'contact' => $contact,
                'psw' => $psw,'openid'=>$openid]);
            if(empty($result)){
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-4];
            }else{
                $result->psw='';
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>1,'data'=>$result];
            }
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }

    //登录
    public function login($phone,$psw,$openid,$avatar,$nick){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $supp_msg=ConsoleAccount::where(['console_account.account'=>$phone,'console_account.types'=>1])
                ->select('console_account.id','console_account.uuid','console_account.is_valid','console_account.types',
                    'console_account.open_id','console_account.password','console_account.avatar','console_account.nick',
                    'supp.id as supp_id','supp.name','supp.phone','supp.email','supp.addr','supp.contact')
                ->leftJoin('supp','supp.phone','=','console_account.account')
                ->first();

            if(empty($supp_msg)){
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-1];
            }else{
                if(Hash::check($psw, $supp_msg->password)){
//                    if($supp_msg->open_id==null||$supp_msg->open_id==''){
//                        $supp_msg->open_id=$openid;
//                    }
//                    if($supp_msg->avatar==null||$supp_msg->avatar==''){
//                        $supp_msg->avatar=$avatar;
//                    }
//                    if($supp_msg->nick==null||$supp_msg->nick==''){
//                        $supp_msg->nick=$nick;
//                    }
                    $supp_msg->open_id=$openid;
                    $supp_msg->avatar=$avatar;
                    $supp_msg->nick=$nick;
                    $supp_msg->save();
                    return ['code'=>1,'data'=> $supp_msg];
                }else{
                    return ['code'=>-1];
                }
            }
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //发送验证码
    public function sendSms($phone,$openid){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            DB::beginTransaction();
            $vcode=rand(100000,999999);
            $sms=new SmsUtils();
            $res=$sms->sendSms($phone,$vcode);

            //保存vcode
            ShopVcode::where('openid',$openid)->delete();
            ShopVcode::create(['openid'=>$openid,'vcode'=>$vcode,'over_time'=>time()+60]);

            if($res){
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                DB::commit();
                return ['code'=>1,'data'=>$vcode];
            }else{
                DB::rollBack();
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-1];
            }
        }catch (Exception $ex) {
            DB::rollBack();
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //验证码验证
    public function vcodeVerify($vcode,$openid){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $shopVcode=ShopVcode::where(['openid'=>$openid,'vcode'=>$vcode])->first();
            if(empty($shopVcode)){
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-1];
            }
            if($shopVcode->over_time<time()){
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-2];//已过期
            }
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code'=>1];

        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //修改密码
    public function updatePsw($supp_id,$old_psw,$new_psw){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            //判断验证码是否一致
            $supp_msg=Supp::find($supp_id);
//            $supp_msg=ConsoleAccount::find($supp_id);
            if(empty($supp_msg)){
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-1];
            }

            $account_msg=ConsoleAccount::where(['account'=>$supp_msg->phone,'types'=>1])->first();
            if(empty($account_msg)){
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-1];
            }
            if(!Hash::check($old_psw, $account_msg->password)){
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-1];
            }
            $account_msg->password=$new_psw;
            $account_msg->save();
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code'=>1];

        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //忘记密码
    public function forgetPsw($phone,$psw){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');

            $account_msg=ConsoleAccount::where(['account'=>$phone,'types'=>1])->first();
            if(empty($account_msg)){
                return ['code'=>-2];
            }
            $account_msg->password=$psw;
            $account_msg->save();

            $res=ConsoleAccount::where(['console_account.account'=>$phone,'console_account.types'=>1])
                ->select('console_account.id','console_account.uuid','console_account.is_valid','console_account.types',
                    'console_account.open_id','console_account.password','supp.id as supp_id',
                    'supp.name','supp.phone','supp.email','supp.addr','supp.contact')
                ->leftJoin('supp','supp.phone','=','console_account.account')
                ->first();
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code'=>1,'data'=>$res];

        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //获取供应商首页数据
    public function getFirstPageMsg($unique_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            //根据unique_id获取用户的信息
            $result=array();
            $suppmsg=Supp::select('id','name','phone')->where('unique_id',$unique_id)->first();
            if(!empty($suppmsg)){
                $result['suppmsg']=$suppmsg;
                $supp_id=$suppmsg->id;
                $result['total_order_money']=$this->getSuppTotalMoney($supp_id,$type=0);
                //查询供应商的总期数
                $result['total_nper']=PtPreSale::where('supp_id',$supp_id)->count();
                $result['latest_nper_msg']=$this->getSuppLatestOrderMsg($supp_id);
            }

            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
//            return response()->json(['code'=>2,
//                'msg'=>'读取成功','data'=>$result]);
            return $result;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }



    //获取供应商最近一器的商品订单统计数据
    public function getSuppTotalMoney($supp_id,$type=0){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');

            $total_order_money=0;
            if($type==0){//查询已结束预约的订单总额

                $total_order_money=PtPreSale::where('end_date','<',date('Y-m-d H:i:s',time()))->where('supp_id',$supp_id)->sum('total_money');
                Log::info('09');
            }else{//查询全部的订单总额
                $total_order_money=PtPreSale::where('supp_id',$supp_id)->sum('total_money');
            }

            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return substr(sprintf('%.3f',$total_order_money/100),0,-1);
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }



    //获取供应商最近一器的商品订单统计数据
    public function getSuppLatestOrderMsg($supp_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');

            $latest_nper_msg=null;
            //查询刚结束的一期的统计数据
            $ptPreSaleMsg=PtPreSale::where('supp_id',$supp_id)->orderBy('end_date','desc')
                ->where('end_date','<',Carbon::now())->first();

            if(!empty($ptPreSaleMsg)){
                $start_time=strtotime($ptPreSaleMsg->start_date);
                $end_time=strtotime($ptPreSaleMsg->end_date);
                $s_year=date('Y',$start_time);//开始日期的年份
                $e_year=date('Y',$end_time);//结束日期的年份
                if($s_year==$e_year){
                    $latest_nper_msg['date']=date('Y.m.d',$start_time).'-'.date('m.d',$end_time);
                }else{
                    $latest_nper_msg['date']=date('Y.m.d',$start_time).'-'.date('Y.m.d',$end_time);
                }

                //查询商品名称
                $goods=PtGoods::find($ptPreSaleMsg->goods_id);
                $latest_nper_msg['goods_name']=$goods->goods_name;
                $latest_nper_msg['total_order_money']=$ptPreSaleMsg->total_money;
                if(empty($ptPreSaleMsg->total_money)){
                    $latest_nper_msg['total_order_money']=0.00;
                }
                $latest_nper_msg['total_order_num']=$ptPreSaleMsg->total_order_num;
                if(empty($ptPreSaleMsg->total_order_num)){
                    $latest_nper_msg['total_order_num']=0;
                }


            }
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return $latest_nper_msg;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }



    //素材商品列表
    public function readGoodsByCondition($supp_id,$where,$account_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $result=array();
            $ptGoods=PtGoods::query();

            //数据权限
            $role_ids = ConsoleAccountRole::where(['account_id'=>$account_id,'ownto_id'=>$supp_id,'account_types'=>1])->pluck('role_id')->all();
            if(count($role_ids) == 0){
                return null;
            }
            $role_ids = array_intersect($role_ids,Consts::admin_role_supp_sub);//去数组的交集
            if(count($role_ids)>0){
                $goods_ids = RoleUtils::getRightData($account_id,$supp_id,1);
                Log::info($goods_ids);
                $ptGoods = $ptGoods->whereIn('id',$goods_ids);
            }

            $goods_name=null;
            if(array_key_exists('goods_name',$where)){
                if($where['goods_name']!=''){
                    $goods_name=$where['goods_name'];
                }
            }
            if($goods_name!=null){
                $ptGoods->where('goods_name','like','%'.$goods_name.'%');
            }

            $result=$ptGoods->select('id','goods_name')
                ->with(['PtMaterial' => function ($query) {
                    $query->select('id','goods_id');
                }])
                ->where('creator_ownto_id',$supp_id)->orderBy('id','desc')->paginate(Consts::PAGE_SIZE);

            if($result->count()>0){
                foreach ($result->items() as $g){
                    $g->status='未添加素材';
                    if($g->PtMaterial!=null&&count($g->PtMaterial)>0){
                        $g->status='已添加素材';
                    }
                    unset($g->PtMaterial);
                }
            }else{
                return null;
            }
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return $result;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //素材商品列表
    public function readGoodsById($id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $result = PtGoods::select('id','goods_name','present_price','original_price',
                'cost_price','goods_profile','goods_detail','published','postage')
                ->where('id',$id)
                ->with(['PtMaterial' => function ($query) {
                    $query->select('id', 'goods_id','desc','material','type','supp_id');
                }])->first();
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return $result;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }




    //修改供应商信息
    public function updateSuppMsg($supp,$supp_id,$phone){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $suppMsg=Supp::find($supp_id);
            if(array_key_exists('phone',$supp)){
                $u_phone=$supp['phone'];
                if($u_phone!=$phone){
                    $p=Supp::where('phone',$u_phone)->first();
                    if(!empty($p)){
                        return ['code'=>-1];//手机号已注册
                    }
                }
            }
            if(array_key_exists('name',$supp)){//公司名称不能修改
                unset($supp['name']);
            }

            if(array_key_exists('sale_end',$supp)){
                //同步供应商添加的所有商品的sale_end
                PtGoods::where(['account_types'=>1,'creator_ownto_id'=>$supp_id])->update(['sale_end'=>$supp['sale_end']]);
            }

            foreach ($supp as $key=>$val){
                $suppMsg->$key=str_pad($val,5,0,STR_PAD_LEFT);
            }
            $suppMsg->save();
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code'=>1];
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }



    //获取供应商信息
    public function readSuppById($supp_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $result = Supp::find($supp_id);
            if(!empty($result)){
                unset($result->psw);
            }
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return $result;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }

    

    //获取供应商的统计信息
    public function readStatMsg($supp_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $supp=Supp::find($supp_id);
            $result=array();
            $result['total_money_data']=null;
            $result['total_order_data']=null;
            $result['total_profits_data']=null;
            if($supp!=null){
                //根据供应商id
                $suppDayStat=SuppDayStat::where('supp_id',$supp_id)->get();
                $total_money_data=array();//总金额图表数据
                $total_order_data=array();//总订单图表数据
                $total_profits_data=array();//总利润图表数据
                $categories=array();
                $money_data=array();
                $order_num_date=array();
                $profits_data=array();
                if($suppDayStat!=null&&count($suppDayStat)>0){
                    foreach ($suppDayStat as $p){
                        //处理时间
                        $categories[]=$p->year.'/'.$p->month.'/'.$p->day;
                        $money_data[]=(float)substr(sprintf('%.3f',($p->total_order_money/100)),0,-1);
                        $order_num_date[]=$p->total_order_num;
                        $profits_data[]=(float)substr(sprintf('%.3f',($p->total_profits/100)),0,-1);
                    }
                    //总金额图表数据
                    $total_money_data['categories']=$categories;
                    $total_money_data['series'][0]['name']='总金额';
                    $total_money_data['series'][0]['data']=$money_data;
                    $total_money_data['yAxis']['title']='总金额（元）';
                    $total_money_data['yAxis']['min']=0;
                    $total_money_data['title']=['name'=>'订单总额','fontSize'=>'16px','color'=>'#123456'];
                    $total_money_data['subtitle']=['name'=>'总额（元）','fontSize'=>'16px','color'=>'#123456'];
                    //总订单图表数据
                    $total_order_data['categories']=$categories;
                    $total_order_data['series'][0]['name']='订单总数';
                    $total_order_data['series'][0]['data']=$order_num_date;
                    $total_order_data['yAxis']['title']='订单总数';
                    $total_order_data['yAxis']['min']=0;
                    $total_order_data['title']=['name'=>'订单总数','fontSize'=>'16px','color'=>'#123456'];
                    $total_order_data['subtitle']=['name'=>'总数（单）','fontSize'=>'16px','color'=>'#123456'];
                    //总利润图表数据
                    $total_profits_data['categories']=$categories;
                    $total_profits_data['series'][0]['name']='总利润';
                    $total_profits_data['series'][0]['data']=$profits_data;
                    $total_profits_data['yAxis']['title']='总利润（元）';
                    $total_profits_data['yAxis']['min']=0;
                    $total_profits_data['title']=['name'=>'总利润','fontSize'=>'16px','color'=>'#123456'];
                    $total_profits_data['subtitle']=['name'=>'利润（元）','fontSize'=>'16px','color'=>'#123456'];

                    if(count($money_data)>0){
                        $result['total_money_data']=$total_money_data;
                    }
                    if(count($order_num_date)>0){
                        $result['total_order_data']=$total_order_data;
                    }
                    if(count($profits_data)>0){
                        $result['total_profits_data']=$total_profits_data;
                    }
                }
            }
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return $result;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //我管理的供应商列表
    public function getShopListBiz($account_id,$supp_id)
    {
        try {
            Log::debug(get_class($this) . ' ' . __FUNCTION__ . ' ' . 'start');
            $supps = ConsoleAccountRole::query()
                ->select('supp.id','supp.name', 'console_role.name as role_name')
                ->leftJoin('console_account', 'console_account.id', '=', 'console_account_role.account_id')
                ->leftJoin('supp', 'supp.id', '=', 'console_account_role.ownto_id')
                ->leftJoin('console_role', 'console_role.id', '=', 'console_account_role.role_id')
                ->where([
                    'console_account_role.account_id'=>$account_id,
                    'console_account.types'=>1,
                    'console_account.is_valid' => '0',
//                    'console_account_role.ownto_id'=>$supp_id
                ])->get();
            Log::info($account_id);
//            Log::info($supp_id);
//            Log::info(ConsoleAccountRole::query()
//                ->select('supp.id','supp.name', 'console_role.name as role_name')
//                ->leftJoin('console_account', 'console_account.id', '=', 'console_account_role.account_id')
//                ->leftJoin('supp', 'supp.id', '=', 'console_account_role.ownto_id')
//                ->leftJoin('console_role', 'console_role.id', '=', 'console_account_role.role_id')
//                ->where([
//                    'console_account_role.account_id'=>$account_id,
//                    'console_account.types'=>1,
//                    'console_account.is_valid' => '0',
//                    'console_account_role.ownto_id'=>$supp_id
//                ])->toSql());
            $user = ConsoleAccount::find($account_id);
            $result['supps'] = $supps;
            $result['user'] = $user;
            Log::debug(get_class($this) . ' ' . __FUNCTION__ . ' ' . 'end');
            return $result;
        } catch (PDOException $ex) {
            Log::error(get_class($this) . ' exception ' . print_r($ex->getMessage(), true));
            return array();
        }
    }

    public function prov_listBiz($flag)
    {
        try {
            Log::debug(get_class($this) . ' ' . __FUNCTION__ . ' ' . 'start');
            Log::info($flag);
            if($flag == 0){
                $provs = PtProv::query()->orderBy('py')->with(['citys.countys.villages'])->get();
            }else if($flag == 2){
                $provs = PtProv::query()->orderBy('py')->get(['name as text','id as value']);
            }else {
                $provs = PtProv::query()->orderBy('py')->get();
            }
            return $provs;
            Log::debug(get_class($this) . ' ' . __FUNCTION__ . ' ' . 'end');
            return $result;
        } catch (PDOException $ex) {
            Log::error(get_class($this) . ' exception ' . print_r($ex->getMessage(), true));
            return array();
        }
    }
}